﻿using System;
using System.Threading.Tasks;
using System.Windows;
using UpdateApp.Config;

namespace UpdateApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private VersionDto _version;
        private Window _mainWindow;

        public App()
        {

        }

        /// <summary>
        /// ctor
        /// </summary>
        public App(string[] args) : this()
        {
            Init(args);
        }

        protected override void OnStartup(StartupEventArgs e)
        {   
            base.OnStartup(e);
        }

        #region private methods
        /// <summary>
        /// 全局异常捕获
        /// </summary>
        private void CatchException()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
            DispatcherUnhandledException += AppDispatcherUnhandledException;
            //TaskScheduler.UnobservedTaskException += TaskSchedulerUnobservedTaskException;
        }

        private void TaskSchedulerUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            e.SetObserved();
            e.Exception.ShowError(_mainWindow);
        }

        private void AppDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            e.Exception.ShowError(_mainWindow);
        }

        private void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception ex)
                ex.ShowError(_mainWindow);
        }

        /// <summary>
        /// 检测是否需要更改
        /// </summary>
        /// <returns></returns>
        private bool IsNeedUpdate()
        {
            _version = Config.Config.VersionUrl.GetVersionAsync().ConfigureAwait(false).GetAwaiter().GetResult() ?? new Config.Config().MapTo();
            var appVer = Helper.GetFileVersion(_version.UpdateApp);
            return appVer.IsUpdate(_version.Version);
        }

        /// <summary>
        /// init
        /// </summary>
        private void Init(string[] args)
        {
            if (args.Length == 1 && args[0].StartsWith("http"))
                Config.Config.VersionUrl = args[0];
            if (!IsNeedUpdate())
            {
                "已是最新版本".ShowInfo();
                Environment.Exit(0);
                return;
            }
            CatchException();
            InitializeComponent();
            _mainWindow = new MainWindow(_version!);
            Run(_mainWindow);
        }
        #endregion
    }
}
